package terrain;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Logger;

import Units.Creatures;

import com.jme3.app.Application;
import com.jme3.asset.AssetManager;
import com.jme3.scene.Node;

public class TerrainMap {
	private static final Logger logger = Logger.getLogger(Application.class
			.getName());
	
	private Node gameNode;
	private TopDown topDown;
	private Wall wall;
	private Creatures creatures;
	
	private TileGlobal [][]map;
	private int []size = new int[2];
	
	public TerrainMap(AssetManager assetManager, Node gameNode) {
		this.gameNode = gameNode;
		topDown = new TopDown(assetManager);
		wall = new Wall(assetManager);
		creatures = new Creatures(assetManager);
		
	}
	
	public boolean loadMap(String mapPath) {
		File f = new File(mapPath);
		if (!f.exists()) {
			logger.warning("Did not found " + mapPath);
			return false;
		}

		try {
			BufferedReader input = new BufferedReader(new FileReader(f));
			try {
				String line = input.readLine();
				if (line == null) {
					throw new IOException();
				}
				String[] split = line.split(";");
				size[0] = Integer.valueOf(split[0]).intValue();
				size[1] = Integer.valueOf(split[1]).intValue();
				map = new TileGlobal[size[0]][size[1]];
				
				for (int y = 0; y < size[1]; y++) {
					line = input.readLine();
					if (line == null) {
						throw new IOException();
					}
					split = line.split(";");
					for (int x = 0; x < size[0]; x++) {
						int type = Integer.valueOf(split[x]).intValue();
						Node tileNode = new Node("Tile Node");
						map[x][y] = new TileGlobal(tileNode, type, x, y, topDown, wall, creatures);
						gameNode.attachChild(tileNode);
					}
				}
				for (int y = 0; y < size[1]; y++) {
					for (int x = 0; x < size[0]; x++) {
						if (y < size[1] - 1)
							map[x][y].getTile().setTileUp(map[x][y+1].getTile());
						if (y > 0)
							map[x][y].getTile().setTileDown(map[x][y-1].getTile());
						if (x < size[0] - 1)
							map[x][y].getTile().setTileRight(map[x+1][y].getTile());
						if (x > 0)
							map[x][y].getTile().setTileLeft(map[x-1][y].getTile());
						
					}
				}
			} finally {
				input.close();
			}
		} catch (IOException e) {
			logger.warning("Tryed loading " + "mapPath" + ", but got an error");
			e.printStackTrace();
		}
		return true;
	}
	
	public void createMap() {	
		for (int x = 0; x < map.length; x++) {
			for (int y = 0; y < map[0].length; y++) {
				map[x][y].getTile().generate();
			}
		}
	}
	
	public void removeTile(int x, int y) {
		map[x][y].getTile().setTop(null);
	}
}
